<template>
  <div class="page flex-column">
    <div class="page-title">文件库</div>
    <div class="page-filter flex-column">
      <div class="total-title">空间容量</div>
      <div class="total-chart">
        <a-progress :percent="getPercent(storeMyMaterial.myOverview.totalSpace, storeMyMaterial.myOverview.remainingSpace)"
          :size="[100,20]" :show-info="false" />
      </div>
      <div class="total-info">
        <div class="all-title">总空间：</div>
        <div class="all-value">{{ formatSize(storeMyMaterial.myOverview.totalSpace) }}</div>
        <div class="left-title">空间剩余：</div>
        <div class="left-value">{{ formatSize(storeMyMaterial.myOverview.remainingSpace) }}</div>
      </div>
    </div>
    <div class="page-result flex-column">
      <div class="result-search">
        <div class="result-title"></div>
        <div v-if="false" class="btn-download">
          <a-button type="primary" danger shape="round"
            @click="doDownload('')"
            style="width: 100%; height: 100%;">
            下载至本地
          </a-button>
        </div>
        <div class="btn-delete">
          <a-button danger shape="round"
            @click="doDelete()"
            style="width: 100%; height: 100%;">
            删除
          </a-button>
        </div>
      </div>

      <!-- 表单区 -->
      <div class="result-list">
        <a-table
          :columns="columns"
          :data-source="storeMyMaterial.materialSource"
          :row-selection="rowSelection"
          :rowKey="record => record.id"
          :pagination="false"
          style="width: 100%">
          <template #headerCell="{ column }">
            <span> {{ column.title }} </span>
          </template>

          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'fileName'">
              <span>
                {{ record.fileName }}
              </span>
            </template>
            <template v-if="column.key === 'fileSize'">
              <span class="gray-text">
                {{ formatSize(record.fileSize) }}
              </span>
            </template>
            <template v-else-if="column.key === 'createdAt'">
              <span class="gray-text">
                {{ record.createdAt }}
              </span>
            </template>
            <template v-else-if="column.key === 'fileExt'">
              <span class="gray-text">
                {{ record.fileExt }}
              </span>
            </template>
            <template v-else-if="column.key === 'action'">
              <a @click="doDownload(record.fileUrl)" class="download-text">
                下载
              </a>
            </template>
          </template>
        </a-table>
      </div>

      <div v-if="totalRecords>pageSize" class="page-pagination flex-row flex-center">
        <a-pagination 
          v-model:current="currentPage"
          v-model:pageSize="pageSize"
          :total="totalRecords"
          @change="storeMyMaterial.handlePageChange"
          show-less-items />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeMount, createVNode } from 'vue';
import { Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { MyMaterial } from "@/models/material"
import useMyMaterialStore from '@/stores/my-material';
import { downloadFile } from '@/utils/download'
import { miscApi } from "@/services";

const storeMyMaterial = useMyMaterialStore();
const currentPage = ref(storeMyMaterial.pageNum);
const pageSize = ref(storeMyMaterial.pageSize);
const totalRecords = ref(0);
const selectedIds = ref<number[]>([]);

const rowSelection = ref({
  checkStrictly: false,
  onChange: (selectedRowKeys: (string | number)[], selectedRows: MyMaterial[]) => {
    // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    const ids:number[] = selectedRows.map((item: MyMaterial) => item.id);
    console.log('selectedIds: ', ids);
    selectedIds.value = ids;
  },
  onSelect: (record: MyMaterial, selected: boolean, selectedRows: MyMaterial[]) => {
    // console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected: boolean, selectedRows: MyMaterial[], changeRows: MyMaterial[]) => {
    // console.log(selected, selectedRows, changeRows);
  },
});
const columns = [
  {
    title: "文件名称",
    dataIndex: "fileName",
    key: "fileName",
    width: "50%",
  },
  {
    title: "文件大小",
    dataIndex: "fileSize",
    key: "fileSize",
    width: "10%",
  },
  {
    title: "创建时间",
    dataIndex: "createdAt",
    key: "createdAt",
    width: "20%",
  },
  {
    title: "文件类型",
    dataIndex: "fileExt",
    key: "fileExt",
    width: "10%",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    width: "10%",
  },
];

onBeforeMount(async () => {
  await storeMyMaterial.initData();

  totalRecords.value = storeMyMaterial.totalRecords;

  await miscApi.traceViewPage("/my-material/list");
});

const getPercent = (total: number, left: number) => {
  return total>0 ? ((total - left) / total * 100) : 0;
};

const byteRadix = 1024;
const formatSize = (size: number) => {
  if (!size || size <= 0) {
    return '0B';
  }

  if (size < byteRadix) {
    return size + 'B';
  } else if (size < byteRadix * byteRadix) {
    return (size / byteRadix).toFixed(2) + 'KB';
  } else if (size < byteRadix * byteRadix * byteRadix) {
    return (size / (byteRadix * byteRadix)).toFixed(2) + 'MB';
  } else {
    return (size / (byteRadix * byteRadix * byteRadix)).toFixed(2) + 'GB';
  }
};

const doDownload = async (url:string) => {
  if (!url) {
    return;
  }

  try {
    const fileName = url.split('/').pop();
    await downloadFile({
      url: url,
      fileName: fileName // 可选自定义文件名‌:ml-citation{ref="6" data="citationList"}
    })
  } catch (error) {
    console.error(`下载文件 ${url} 出现异常`, error);
  }
}

const doDelete = async () => {
  if (selectedIds.value && selectedIds.value.length <=0) {
    Modal.info({
      title: '请先选择要删除的文件',
      content: '',
      okText: '确定',
    });
    return;
  }

  Modal.confirm({
    title: '确定要删除选定的文件吗?',
    icon: createVNode(ExclamationCircleOutlined),
    content: '',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      await storeMyMaterial.deleteMyMaterials(selectedIds.value);
      totalRecords.value = storeMyMaterial.totalRecords;
    },
  });
};
</script>

<style lang="less" scoped>
.page {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  background-color: @white-bg;

  .page-title {
    height: 24px;
    line-height: 24px;
    font-size: 20px;
    font-weight: 500;
    color: @font-black;
    padding: 20px 30px;
  }

  .page-filter {
    height: 146px;
    background: @white;
    border-radius: 20px;
    margin: 20px 30px 0 30px;
    padding: 30px 20px;

    .total-title {
      width: 200x;
      height: 16px;
      line-height: 16px;
      color: @font-black;
      font-size: 16px;
      font-weight: 500;
    }

    .total-chart {
      margin-top: 20px;
    }

    .total-info {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-items: center;
      margin-top: 8px;

      .all-title, .left-title {
        height: 16px;
        line-height: 16px;
        font-size: 16px;
        font-weight: 400;
        color: @font-grey;
      }
      .all-value, .left-value {
        height: 20px;
        line-height: 20px;
        font-size: 20px;
        font-weight: 500;
        color: @font-black;
      }
      .left-title {
        margin-left: 50px;
      }
      .left-value {
        flex: 1;
      }
    }
  }

  .page-result {
    background-color: @white;
    border-radius: 20px;
    margin: 20px 30px;

    .result-search {
      height: 24px;
      padding: 20px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-items: center;
      margin-top: 20px;

      .result-title {
        flex: 1;
        height: 24px;
        line-height: 24px;
        font-size: 20px;
        font-weight: 500;
        color: @font-black;
      }

      .btn-download {
        width: 160px;
      }

      .btn-delete {
        margin-left: 20px;
        width: 100px;
      }
    }

    .result-list {
      margin: 16px 20px 0 20px;
      padding-bottom: 20px;
    }

    :deep(.ant-table-wrapper) {
      .ant-table {
        font-size: 16px;
      }
      .ant-checkbox-wrapper {
        padding-left: 16px;
      }
    }
  }
  .page-pagination {
    width: 100%;
    padding: 10px 30px 50px 30px;
  }

  .gray-text {
    color: @font-grey;
  }
  .download-text {
    color: @font-red;
  }
}

:deep(.ant-table-wrapper .ant-table-thead >tr>th) {
  color: @font-black;
  background-color: @pink-table-hd;
}



:deep(.ant-pagination) {
  .ant-pagination-item {
    min-width: 44px;
    height: 44px;
    margin-inline-end: 10px;
    line-height: 44px;
    background-color: @white;
    border: 1px solid @border-red-light;
    border-radius: 50%;

    a {
      font-size: 14px;
      font-weight: 400;
    }

    &.ant-pagination-item-active {
      border: 1px solid #ED171F;
    }
  }
  .ant-pagination-prev, .ant-pagination-next, .ant-pagination-jump-prev, .ant-pagination-jump-next {
    min-width: 44px;
    height: 44px;
    color: @font-black;
    line-height: 44px;
    border: 1px solid @border-red-light;
    border-radius: 50%;
    margin-inline-end: 10px;

    a {
      font-size: 14px;
      font-weight: 400;
      border-radius: 50%;
    }
  }

  .ant-pagination-prev:hover .ant-pagination-item-link, .ant-pagination-next:hover .ant-pagination-item-link {
    background-color: rgba(0, 0, 0, 0.06);
  }

  .ant-pagination-prev .ant-pagination-item-link, .ant-pagination-next .ant-pagination-item-link {
    border-radius: 50%;
  }

  .ant-pagination-options {
    display: none;
  }
}

:deep(.ant-btn) {
  font-size: 16px;

  &.ant-btn-round {
    border-radius: 20px;
  }
}

:deep(.ant-btn-default.ant-btn-dangerous) {
  color: @font-red;
  border-color: @font-red;
}
</style>
